package com.joven.shelltest.test;

import com.google.common.util.concurrent.RateLimiter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Guava RateLimiter
 */
public class OtherTest6 {
    public static void main(String[] args) {
        //限流器流速：2个请求/秒
        RateLimiter limiter = RateLimiter.create(2.0);
        //执行任务的线程池
        ExecutorService es = Executors.newFixedThreadPool(1);

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        //测试执行20次
        for (int i = 0; i < 20; i++) {
            es.execute(() -> {
                boolean tryAcquire = limiter.tryAcquire(500, TimeUnit.MILLISECONDS);

                if (!tryAcquire) {
                    System.out.println("进入服务降级，时间:" + LocalDateTime.now().format(dtf));
                }
                System.out.println("获取令牌成功，时间{}:" + LocalDateTime.now().format(dtf));
            });
        }
    }
}
